import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"
import axios from "axios"

interface UserState {
  loading: boolean,
  error: string | null,
  token: string | null
}

const initialState: UserState = {
  loading: false,
  error: null,
  token: null,
}

export const sinIn = createAsyncThunk(
  'user/sinIn',
  async (paramaters: { email: string, password:  string }, thunkAPI) => {
    let url = `http://82.157.43.234:8080/auth/login`
    const {data} = await axios.post(url, {
      email: paramaters.email,
      password: paramaters.password
    } ,{
      headers: {
        'x-icode': 'EDE45279EB142953'
      }
    })
    return data.token

  }
)


export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logOut: (state) => {
      state.loading = false
      state.error = null
      state.token = null
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(sinIn.pending, (state) => {
        state.loading = true
      })
      .addCase(sinIn.fulfilled, (state, action) => {
        state.token = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(sinIn.rejected, (state, action) => {
        state.loading = false
        if (typeof action.payload === 'string') {
          state.error = action.payload
        } else {
          state.error = null
        }

      })
  }
})